/*
 * @Author: EyeSklear 1814580085@qq.com
 * @Date: 2024-01-10 13:00:15
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-05-14 15:47:12
 * @FilePath: \Scene_Back\src\audio\audio.controller.ts
 * @Description:
 *
 * Copyright (c) 2024 by EyeSklear , All Rights Reserved.
 */
import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Res,
  UseInterceptors,
  UploadedFile,
  HttpStatus,
  Req,
} from '@nestjs/common';
import { AudioService } from './audio.service';
import { CreateAudioDto, RawAudioDto } from './dto/create-audio.dto';
import { UpdateAudioDto } from './dto/update-audio.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response, Request } from 'express';
import * as fs from 'fs';
import * as path from 'path';

@Controller('audio')
export class AudioController {
  constructor(private readonly audioService: AudioService) {}

  @Post('createAudioItem')
  create(@Body() rawAudioDto: RawAudioDto, @Req() request: Request) {
    const user = request.user;
    rawAudioDto.creator = (user as any).email;
    return this.audioService.create(rawAudioDto);
  }
  @Post('singleAudioItem')
  @UseInterceptors(FileInterceptor('file'))
  uploadAudio(@UploadedFile() file) {
    return file.filename;
  }

  @Get('getAudioSrc/:filename')
  getExampleAudio(
    @Res() res: Response,
    @Param('filename') filename: string,
  ): void {
    const audioFilePath = path.resolve(
      process.env.FILE_PATH + '/audio/' + filename,
    );
    if (!fs.existsSync(audioFilePath)) {
      console.error('MP3 file does not exist.');
      res.status(HttpStatus.NOT_FOUND).send('MP3 file not found');
      return; // 或者执行其他逻辑
    }

    const stat = fs.statSync(audioFilePath);
    const fileSize = stat.size;
    const range = res.req.headers.range;

    if (range) {
      const parts = range.replace(/bytes=/, '').split('-');
      const start = parseInt(parts[0], 10);
      const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

      const chunksize = end - start + 1;
      const file = fs.createReadStream(audioFilePath, { start, end });
      const head = {
        'Content-Range': `bytes ${start}-${end}/${fileSize}`,
        'Accept-Ranges': 'bytes',
        'Content-Length': chunksize,
        'Content-Type': 'audio/mp3',
      };

      res.writeHead(206, head);
      file.pipe(res);
    } else {
      const head = {
        'Content-Length': fileSize,
        'Content-Type': 'audio/mp3',
      };
      res.writeHead(200, head);
      fs.createReadStream(audioFilePath).pipe(res);
    }
  }

  @Get('findAll')
  findAll() {
    return this.audioService.findAll();
  }

  @Get('findOne/:id')
  findOne(@Param('id') id: string) {
    return this.audioService.findOne(id);
  }

  @Patch('update/:id')
  update(@Param('id') id: string, @Body() updateAudioDto: UpdateAudioDto) {
    return this.audioService.update(id, updateAudioDto);
  }

  @Delete('remove/:id')
  remove(@Param('id') id: string) {
    return this.audioService.remove(id);
  }
}
